package io.renren;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.convert.converter.Converter;

//import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;

import io.renren.datasources.DynamicDataSourceConfig;

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@Import({ DynamicDataSourceConfig.class })
//@EnableDubboConfiguration
public class RenrenApplication extends SpringBootServletInitializer {

	public static void main(String[] args) {
		SpringApplication.run(RenrenApplication.class, args);
	}

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(RenrenApplication.class);
	}

	private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
	private static final String shortDateFormat = "yyyy-MM-dd";

	@Bean
	public Converter<String, Date> addDateConvert() {
		return new Converter<String, Date>() {
			@Override
			public Date convert(String source) {
				if (StringUtils.isBlank(source)) {
					return null;
				}
				source = source.trim();
				try {
					if (source.contains("-")) {
						SimpleDateFormat formatter;
						if (source.contains(":")) {
							formatter = new SimpleDateFormat(dateFormat);
						} else {
							formatter = new SimpleDateFormat(shortDateFormat);
						}
						return formatter.parse(source);
					} else if (source.matches("^\\d+$")) {
						Long lDate = new Long(source);
						return new Date(lDate);
					}
				} catch (Exception e) {
					throw new RuntimeException(String.format("parser %s to Date fail", source));
				}
				throw new RuntimeException(String.format("parser %s to Date fail", source));
			}
		};
	}

}
